#ifdef WIN32
	#include <winsock2.h>
#else
	#include <netdb.h> // gethostbyname()
	#include <netinet/in.h> // struct sockaddr_in
	#include <sys/socket.h> // socket()
#endif
#include <stdio.h>
#include <string.h>
#include <unistd.h> // close

void CloseConnection(int *sockfd)
{
#ifdef WIN32
	closesocket(*sockfd);
	WSACleanup();
#else
	close(*sockfd);
#endif
}

int CreateConnection(int *sockfd, char *hostname)
{
#ifdef WIN32
	WSADATA wsaData;
#endif
	struct hostent *host;
	struct sockaddr_in address;

#ifdef WIN32
	if (WSAStartup(0x202,&wsaData) == SOCKET_ERROR)
	{
		WSACleanup();
		return -1;
	}
#endif

	if( !hostname || (*sockfd=socket(AF_INET, SOCK_STREAM, 0)) == -1 )
		return -1;

	if( (host=gethostbyname(hostname)) == NULL )
	{
		CloseConnection(sockfd);
		return -1;
	}

	memset(&address, 0, sizeof(address));
	address.sin_family = AF_INET;
	address.sin_port = htons(80);
	address.sin_addr.s_addr = *((unsigned long *)host->h_addr);

	if( connect(*sockfd, (struct sockaddr *)&address, sizeof(struct sockaddr)) == -1 )
	{
		CloseConnection(sockfd);
		return -1;
	}

	return 0;
}

int SendData(int sockfd, char *output)
{
	if( !output )
		return -1;
		
	send(sockfd, output, strlen(output), 0);
	return 0;
}

int ReceiveData(int sockfd, char *output, int output_size)
{
	static char *ContentLengthTag = "Content-Length: ";
	int ByteRead, TotalRead=0, ContentLength=65535;
	char *cp, buffer[65535];

	memset(output, 0, output_size);

	while( TotalRead < ContentLength )
	{
		memset(buffer, 0, sizeof(buffer));
		if( (ByteRead=recv(sockfd, buffer, sizeof(buffer)-1, 0)) == -1 )
			return -1;

		cp = buffer;

		if( TotalRead == 0 )
		{
			if( (cp=strstr(buffer, ContentLengthTag)) == NULL )
				return -1;

			cp += strlen(ContentLengthTag);
			sscanf(cp, "%d", &ContentLength);

			if( (cp=strstr(cp, "\r\n\r\n")) == NULL )
				return -1;
			cp += 4;

		}

		ByteRead -= cp - buffer;

		memcpy(output+TotalRead, cp, ByteRead);

		TotalRead += ByteRead;
	}

//	printf("ContentLength=%d TotalRead=%d\n", ContentLength, TotalRead);
	return 0;
}
